#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , simpleOpenNIViewerThreadExists(false)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    DeleteSimpleOpenNIViewerThread();
    delete ui;
}

void MainWindow::DeleteSimpleOpenNIViewerThread()
{
    qDebug() << "DeleteSimpleOpenNIViewerThread: simpleOpenNIViewerThreadExists" << simpleOpenNIViewerThreadExists;

    if (simpleOpenNIViewerThreadExists)
        SimpleOpenNIViewerThreadFinished();
}

void MainWindow::on_Go_pushButton_clicked()
{
    qDebug() << "on_Go_pushButton_clicked:";
    DeleteSimpleOpenNIViewerThread();
    simpleOpenNIViewer = new SimpleOpenNIViewer(this);
    connect(simpleOpenNIViewer,SIGNAL(ObjectFoundStatus(const QString&)),
            ui->statusBar,SLOT(showMessage(const QString&)));

    connect(simpleOpenNIViewer,SIGNAL(finished()),this,SLOT(SimpleOpenNIViewerThreadFinished()));
    simpleOpenNIViewer->start();
    simpleOpenNIViewerThreadExists = true;
    qDebug() << "on_Go_pushButton_clicked: finished calling";
}

void MainWindow::SimpleOpenNIViewerThreadFinished()
{
    qDebug() << "SimpleOpenNIViewerThreadFinished:";

    simpleOpenNIViewerThreadExists = false;

    qDebug() << "SimpleOpenNIViewerThreadFinished: StopThread" ;
    simpleOpenNIViewer->StopThread();

    qDebug() << "SimpleOpenNIViewerThreadFinished: wait(500)";
    simpleOpenNIViewer->wait(500);

    qDebug() << "SimpleOpenNIViewerThreadFinished: isRunning" << simpleOpenNIViewer->isRunning();
    if (simpleOpenNIViewer->isRunning())
    {
        qDebug() << "SimpleOpenNIViewerThreadFinished: deleteLater";
        simpleOpenNIViewer->deleteLater();
        qDebug() << "SimpleOpenNIViewerThreadFinished: deleted";
    }

    qDebug() << "SimpleOpenNIViewerThreadFinished: end";
}

void MainWindow::on_Stop_pushButton_clicked()
{
    qDebug() << "on_Stop_pushButton_clicked:";
    DeleteSimpleOpenNIViewerThread();
}
